package com.utils;

import com.exception.LoginTimeOutException;
import com.vo.LoginData;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class SessionUtil {
    public static HttpSession getSessionFromRequest(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request.getSession();
    }

    public static LoginData getCurrentUser(){
        HttpSession sessionFromRequest = getSessionFromRequest();
        if (sessionFromRequest!=null && sessionFromRequest.getAttribute("curUser")!=null){
            LoginData data = (LoginData) sessionFromRequest.getAttribute("curUser");
            if(ObjectUtils.isEmpty(data)){
                throw  new LoginTimeOutException("登录超时,请重新登录");
            }
            return data;
        }else {
            return null;
        }
    }

    public static Integer getCurrentUserType(){
        LoginData currentUser = getCurrentUser();
        if (currentUser!=null){
            return currentUser.getUserType();
        }else {
            return null;
        }
    }

    public static Long getCurrentUserId(){
        LoginData currentUser = getCurrentUser();
        if (currentUser!=null){
            return currentUser.getUserId();
        }else {
            return null;
        }
    }
    public static Long getCurrentUserLeaderId(){
        LoginData currentUser = getCurrentUser();
        if (currentUser!=null && getCurrentUserType()!=1){
            return currentUser.getLeaderId();
        }else {
            return null;
        }
    }

}
